// pages/messages/messages.ts
import { MerchantAPI } from '../../utils/api'

interface MessageSession {
  sessionId: string;
  msgType: string; // 'customer', 'platform', 'group'
  userInfo?: {
    userId: string;
    userName: string;
    phoneSuffix: string;
    avatar: string;
    isOnline?: boolean;
  };
  senderInfo?: {
    senderId: string;
    senderName: string;
    avatar: string;
  };
  lastMessage: {
    content: string;
    sentAt: string;
    isRead: boolean;
    senderType: string;
    messageId?: string;
  };
  unreadCount: number;
  relatedOrder?: {
    orderId: string;
    status: string;
  };
  compositeKey?: string;
}

interface ChatMessage {
  messageId: string;
  senderType: string; // 'user', 'merchant', 'system'
  senderId: string;
  content: string;
  messageType: string; // 'text', 'coupon', 'group_invite'
  sentAt: string;
  isRead: boolean;
  couponInfo?: {
    couponId: string;
    title: string;
    amount: number;
    minOrderAmount: number;
    expireAt: string;
  };
  groupInfo?: {
    groupId: string;
    title: string;
    memberCount: number;
  };
}

interface MessagesPageData {
  hasLogin: boolean;
  loading: boolean;
  refreshing: boolean;
  filterType: 'all' | 'customer' | 'platform' | 'group';
  shouldRefresh: boolean;
  
  // 服务评分
  serviceScore: {
    score: number;
    period: string;
    trend: string;
  };
  
  // 未读消息统计
  unreadCount: {
    total: number;
    customer: number;
    platform: number;
    group: number;
  };
  messageStats: {
    total: number;
    customer: number;
    platform: number;
    group: number;
  };
  unreadStats: {
    total: number;
    customer: number;
    platform: number;
    group: number;
  };
  
  // 消息列表
  messages: MessageSession[];
  
  // 分页
  page: number;
  limit: number;
  hasMore: boolean;
  
  // 状态栏高度
  statusBarHeight: number;
  navBarHeight: number;
  
  // 聊天功能
  showChatModal: boolean;
  currentSession: MessageSession | null;
  chatMessages: ChatMessage[];
  messageInput: string;
  quickReplies: string[];
  scrollTop: number;
  scrollIntoView: string;
  
  // 优惠券功能
  showCouponModal: boolean;
  availableCoupons: any[];
  selectedCoupon: any;
  customMessage: string;
}

Page({
  _currentRequestId: 0, // 用于防止并发请求
  
  data: {
    hasLogin: false,
    loading: false,
    refreshing: false,
    shouldRefresh: false,
    
    // 服务评分
    serviceScore: {
      score: 100,
      period: '近7日',
      trend: 'up'
    },
    
    // 未读消息统计
    unreadCount: {
      total: 1,
      customer: 1,
      platform: 0,
      group: 0
    },
    
    messageStats: {
      total: 0,
      customer: 0,
      platform: 0,
      group: 0
    },
    
    unreadStats: {
      total: 0,
      customer: 0,
      platform: 0,
      group: 0
    },
    
    // 消息列表
    messages: [],
    
    // 分页
    page: 1,
    limit: 10,
    hasMore: true,
    
    // 聊天功能
    showChatModal: false,
    currentSession: null,
    chatMessages: [],
    messageInput: '',
    quickReplies: [],
    scrollTop: 0,
    scrollIntoView: '',
    
    // 优惠券功能
    showCouponModal: false,
    availableCoupons: [],
    selectedCoupon: null,
    customMessage: '',
    
    // 状态栏高度
    statusBarHeight: 0,
    navBarHeight: 0,
    
    // 默认筛选全部
    filterType: 'all'
  } as MessagesPageData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const navBarHeight = statusBarHeight + 44;
    
    // 重置分页和数据 - 使用对象直接赋值确保值正确
    this.data.page = 1;
    this.data.messages = [];
    this.data.hasMore = true;
    
    this.setData({
      statusBarHeight,
      navBarHeight,
      page: 1,
      messages: [],
      hasMore: true
    });
    
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      this.loadMessageStatistics();
      // 延迟一下确保setData完成
      setTimeout(() => {
        this.loadMessages(true);  // 首次加载使用刷新模式
      }, 100);
    }
  },

  onShow() {
    this.checkLoginStatus();
    // 返回时如需刷新或当前无数据，则重新加载
    if (this.data.hasLogin && (this.data.shouldRefresh || (this.data.messages.length === 0 && !this.data.loading))) {
      this.setData({
        shouldRefresh: false,
        page: 1,
        messages: [],
        hasMore: true
      });
      this.loadMessages(true);
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true
      });
    } else {
      this.setData({
        hasLogin: false
      });
    }
  },

  // 去登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  /**
   * 加载消息统计数据
   */
  async loadMessageStatistics() {
    try {
      const response = await MerchantAPI.getMessageStatistics();
      
      if (response.code === 200 && response.data) {
        this.setData({
          serviceScore: response.data.serviceScore || this.data.serviceScore
        });
        
        if (response.data.unreadCount) {
          this.setData({
            unreadStats: {
              total: Number(response.data.unreadCount.total) || 0,
              customer: Number(response.data.unreadCount.customer) || 0,
              platform: Number(response.data.unreadCount.platform) || 0,
              group: Number(response.data.unreadCount.group) || 0
            }
          });
        }
      }
    } catch (error) {
      console.error('加载消息统计失败:', error);
      // 统计数据加载失败不影响主要功能，不显示错误提示
    }
  },

  /**
   * 加载消息会话列表
   */
  async loadMessages(isRefresh = false) {
    // 如果正在加载，直接返回（防止重复请求）
    if (this.data.loading) {
      console.log('正在加载中，跳过本次请求');
      return;
    }
    
    // 添加请求标记，防止并发请求
    const requestId = Date.now();
    this._currentRequestId = requestId;

    // 确定要使用的页码
    let pageNum = 1;
    if (isRefresh) {
      // 刷新模式，强制使用第1页
      pageNum = 1;
      this.data.page = 1;
      this.data.messages = [];
      this.data.hasMore = true;
      
      this.setData({
        page: 1,
        messages: [],
        hasMore: true
      });
    } else {
      // 加载更多模式
      if (!this.data.hasMore) {
        console.log('没有更多数据，跳过本次请求');
        return;
      }
      pageNum = this.data.page || 1;
      if (pageNum < 1) {
        pageNum = 1;
        this.data.page = 1;
        this.setData({ page: 1 });
      }
    }

    this.setData({ 
      loading: true,
      refreshing: isRefresh 
    });

    try {
      console.log('开始加载消息列表, isRefresh:', isRefresh, 'page:', pageNum, 'limit:', this.data.limit, 'requestId:', requestId);
      
      // 调用后端API：获取消息会话列表
      const response = await MerchantAPI.getMessageSessions({
        pageNum: pageNum,
        pageSize: this.data.limit
      });
      
      // 检查是否是当前请求（防止旧请求覆盖新数据）
      if (this._currentRequestId !== requestId) {
        console.log('请求已过期，忽略响应, current:', this._currentRequestId, 'request:', requestId);
        return;
      }
      
      console.log('API响应:', response);

      if (response.code === 200) {
        // 后端返回的是 TableDataInfo 格式，数据在 rows 字段中
        let newSessions = response.rows || [];
        
        console.log('收到会话数据:', JSON.stringify(newSessions, null, 2));
        console.log('数据总数:', response.total);
        console.log('第一条数据示例:', newSessions[0]);
        
        // 确保数据格式正确
        if (!Array.isArray(newSessions)) {
          console.error('返回的数据不是数组:', newSessions);
          newSessions = [];
        }
        
        // 检查数据完整性
        newSessions.forEach((session: any, index: number) => {
          if (!session) {
            console.warn(`第${index}条数据为空`);
          } else {
            console.log(`第${index}条数据 - sessionId: ${session.sessionId}, msgType: ${session.msgType}, hasUserInfo: ${!!session.userInfo}, hasLastMessage: ${!!session.lastMessage}`);
          }
        });
        
        // 处理数据格式，确保所有字段都正确
        newSessions = newSessions.map((session: any, index: number) => {
          if (!session) return null;
          
          const normalizedSessionId = session.sessionId != null
            ? String(session.sessionId)
            : `temp_${index}_${Date.now()}`;

          const formatDateTime = (value: any) => {
            if (!value) {
              return '';
            }
            if (typeof value === 'string') {
              return value;
            }
            try {
              return new Date(value).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-');
            } catch (err) {
              return String(value);
            }
          };

          const normalizedLastMessage = session.lastMessage ? {
            content: session.lastMessage.content || '',
            sentAt: formatDateTime(session.lastMessage.sentAt),
            isRead: Boolean(session.lastMessage.isRead),
            senderType: session.lastMessage.senderType || 'user',
            messageId: session.lastMessage.messageId != null ? String(session.lastMessage.messageId) : undefined
          } : {
            content: '',
            sentAt: '',
            isRead: false,
            senderType: 'user',
            messageId: undefined
          };

          const unreadCountNumber = Number(session.unreadCount);
          const normalizedUnreadCount = Number.isFinite(unreadCountNumber) && !Number.isNaN(unreadCountNumber)
            ? unreadCountNumber
            : 0;

          const normalizedSession: MessageSession = {
            sessionId: normalizedSessionId,
            msgType: session.msgType || 'customer',
            userInfo: session.userInfo ? {
              userId: session.userInfo.userId != null ? String(session.userInfo.userId) : '',
              userName: session.userInfo.userName || '用户',
              phoneSuffix: session.userInfo.phoneSuffix != null ? String(session.userInfo.phoneSuffix) : '',
              avatar: session.userInfo.avatar || '/images/default-avatar.png',
              isOnline: Boolean(session.userInfo.isOnline)
            } : undefined,
            senderInfo: session.senderInfo ? {
              senderId: session.senderInfo.senderId != null ? String(session.senderInfo.senderId) : '',
              senderName: session.senderInfo.senderName || '系统消息',
              avatar: session.senderInfo.avatar || '/images/default-avatar.png'
            } : undefined,
            lastMessage: normalizedLastMessage,
            unreadCount: normalizedUnreadCount,
            relatedOrder: session.relatedOrder ? {
              orderId: session.relatedOrder.orderId != null ? String(session.relatedOrder.orderId) : '',
              status: session.relatedOrder.status || ''
            } : undefined,
            compositeKey: `${normalizedSessionId}_${session.msgType || 'unknown'}`
          };

          return normalizedSession;
        }).filter((session: MessageSession | null): session is MessageSession => session !== null);
        
        // 去重：根据 sessionId + msgType 组合去重（因为同一个sessionId可能有不同类型的消息）
        const sessionMap = new Map<string, MessageSession>();
        newSessions.forEach((session: MessageSession, index: number) => {
          if (!session) {
            console.warn('发现空的会话数据，索引:', index);
            return;
          }
          
          // 使用 sessionId + msgType 作为唯一key，因为同一个sessionId可能有不同类型的消息
          const key = session.compositeKey || (session.sessionId != null 
            ? `${session.sessionId}_${session.msgType || 'unknown'}` 
            : `temp_${index}`);
          
          if (!sessionMap.has(key)) {
            sessionMap.set(key, session);
          } else {
            // 如果已存在，保留最新的（通常后面的更新）
            console.log('发现重复会话，sessionId:', session.sessionId, 'msgType:', session.msgType);
            sessionMap.set(key, session);
          }
        });
        newSessions = Array.from(sessionMap.values());
        
        const total = response.total || 0;
        let allMessages = isRefresh ? newSessions : [...this.data.messages, ...newSessions];
        
        // 对合并后的列表也进行去重（使用相同的key策略）
        const allSessionMap = new Map<string, MessageSession>();
        allMessages.forEach((session: MessageSession, index: number) => {
          if (!session) return;
          
          const key = (session as any).compositeKey || (session.sessionId != null 
            ? `${session.sessionId}_${session.msgType || 'unknown'}` 
            : `temp_${index}`);
          if (!allSessionMap.has(key)) {
            allSessionMap.set(key, session);
          }
        });
        allMessages = Array.from(allSessionMap.values());

        console.log('处理后的会话数量:', allMessages.length);
        console.log('处理后的数据示例:', allMessages.length > 0 ? JSON.stringify(allMessages[0], null, 2) : '无数据');

        // 更新页码：只有在成功获取到数据后才递增页码
        // 使用局部变量pageNum而不是this.data.page，避免异步问题
        const nextPage = newSessions.length > 0 ? pageNum + 1 : pageNum;
        
        // 如果后端返回total为0但实际有数据，使用实际数据长度判断
        const hasMoreData = newSessions.length > 0 && (total > 0 ? allMessages.length < total : newSessions.length >= this.data.limit);

        // 更新data对象
        this.data.page = nextPage;
        this.data.messages = allMessages;
        this.data.hasMore = hasMoreData;

        console.log('准备设置数据 - messages数量:', allMessages.length, 'hasMore:', hasMoreData, 'nextPage:', nextPage);
        console.log('准备设置的数据内容:', JSON.stringify(allMessages, null, 2));
        
        // 强制清空并重新设置，确保视图更新
        this.setData({
          messages: []
        }, () => {
          // 立即设置新数据
          this.setData({
            messages: allMessages,
            hasMore: hasMoreData,
            page: nextPage
          }, () => {
            // setData完成后的回调
            console.log('setData完成 - 当前messages数量:', this.data.messages.length);
            console.log('setData完成 - 第一条消息:', this.data.messages.length > 0 ? JSON.stringify(this.data.messages[0], null, 2) : '无');
            
            // 强制更新视图
            if (this.data.messages.length > 0) {
              console.log('✅ 数据已设置，应该显示', this.data.messages.length, '条消息');
            } else {
              console.error('❌ 数据设置失败，messages为空');
            }

          this.updateMessageStatsFromList(this.data.messages);
          });
        });
        
        console.log('设置后的状态 - messages数量:', allMessages.length, 'hasMore:', hasMoreData, 'nextPage:', nextPage, '当前pageNum:', pageNum);

        // 刷新时同时加载统计数据
        if (isRefresh) {
          this.loadMessageStatistics();
        }
      } else {
        console.error('API返回错误:', response);
        wx.showToast({
          title: response.msg || '加载失败',
          icon: 'none'
        });
      }

    } catch (error) {
      console.error('加载消息列表失败:', error);
      wx.showToast({
        title: '加载失败，请稍后重试',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  /**
   * 根据消息列表计算统计数据
   */
  updateMessageStatsFromList(messages: MessageSession[]) {
    const stats = {
      total: 0,
      customer: 0,
      platform: 0,
      group: 0
    };
    
    const unreadStats = {
      total: 0,
      customer: 0,
      platform: 0,
      group: 0
    };

    if (!Array.isArray(messages) || messages.length === 0) {
      this.setData({
        messageStats: stats,
        unreadStats: unreadStats
      });
      return;
    }

    messages.forEach((session: MessageSession) => {
      const msgType = session?.msgType || 'customer';
      stats.total += 1;
      switch (msgType) {
        case 'platform':
          stats.platform += 1;
          break;
        case 'group':
          stats.group += 1;
          break;
        default:
          stats.customer += 1;
          break;
      }

      const unreadCount = Number((session as any)?.unreadCount) || 0;
      const hasUnread = unreadCount > 0 || (session.lastMessage && session.lastMessage.isRead === false);
      if (hasUnread) {
        unreadStats.total += 1;
        switch (msgType) {
          case 'platform':
            unreadStats.platform += 1;
            break;
          case 'group':
            unreadStats.group += 1;
            break;
          default:
            unreadStats.customer += 1;
            break;
        }
      }
    });

    this.setData({
      messageStats: stats,
      unreadStats: unreadStats
    });
  },

  /**
   * 进入聊天室
   */
  enterChatRoom(e: any) {
    const { index } = e.currentTarget.dataset || {};
    if (index === undefined || index === null) {
      console.warn('未获取到消息索引，无法进入聊天');
      return;
    }

    const session = this.data.messages[index];
    if (!session) {
      console.warn('未找到对应的会话数据，索引:', index);
      return;
    }
    
    if (session.msgType !== 'customer') {
      // 非客户消息，直接显示内容
      wx.showModal({
        title: session.senderInfo?.senderName || '系统消息',
        content: session.lastMessage.content,
        showCancel: false
      });
      
      // 标记为已读
        if (session.unreadCount > 0) {
          const lastMsgId = session.lastMessage?.messageId;
          const ids = lastMsgId ? [lastMsgId] : [];
          this.markSessionAsRead(session.sessionId, ids);
      }
      return;
    }

    // 跳转到聊天详情页面
    const sessionInfoStr = encodeURIComponent(JSON.stringify(session));
    
    this.setData({
      shouldRefresh: true
    });
    
    wx.navigateTo({
      url: `/pages/chat-detail/chat-detail?sessionId=${session.sessionId}&sessionInfo=${sessionInfoStr}`
    });
  },

  /**
   * 加载聊天记录
   */
  async loadChatHistory(sessionId: string, session?: MessageSession) {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 调用后端API：获取会话聊天记录
      const response = await MerchantAPI.getSessionHistory(sessionId, {
        pageNum: 1,
        pageSize: 50
      });

      let chatMessages: ChatMessage[] = [];
      let quickReplies: string[] = [];

      // 后端返回的是 TableDataInfo 格式，数据在 rows 字段中
      if (response.code === 200) {
        chatMessages = (response.rows || []).map((msg: any) => {
          // 确保ID类字段使用字符串避免精度丢失
          const normalizedMessageId = msg.messageId != null ? String(msg.messageId) : `${Date.now()}_${Math.random().toString(36).slice(2)}`;
          const normalizedSenderId = msg.senderId != null ? String(msg.senderId) : '';

          // 格式化时间
          let sentAtText = '';
          const rawSentAt = msg.sentAt;
          if (typeof rawSentAt === 'string') {
            sentAtText = rawSentAt;
          } else if (rawSentAt) {
            sentAtText = new Date(rawSentAt).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-');
          } else {
            sentAtText = new Date().toLocaleString('zh-CN');
          }

          let couponInfo = msg.couponInfo;
          if (couponInfo) {
            couponInfo = {
              ...couponInfo,
              couponId: couponInfo.couponId != null ? String(couponInfo.couponId) : ''
            };
          }

          let groupInfo = msg.groupInfo;
          if (groupInfo) {
            groupInfo = {
              ...groupInfo,
              groupId: groupInfo.groupId != null ? String(groupInfo.groupId) : ''
            };
          }

          return {
            ...msg,
            messageId: normalizedMessageId,
            senderId: normalizedSenderId,
            sentAt: sentAtText,
            couponInfo,
            groupInfo
          };
        });
      }

      // 设置默认快捷回复
      quickReplies = [
        "用餐愉快",
        "订单处理中", 
        "抱歉不便",
        "配送进度",
        "联系我"
      ];

      // 如果没有session参数，从当前数据中获取
      const currentSession = session || this.data.currentSession;
      if (!currentSession) {
        wx.hideLoading();
        wx.showToast({
          title: '会话信息不存在',
          icon: 'none'
        });
        return;
      }

      this.setData({
        showChatModal: true,
        currentSession: currentSession,
        chatMessages: chatMessages,
        quickReplies: quickReplies
      });

      wx.hideLoading();

      // 滚动到底部
      setTimeout(() => {
        this.scrollToBottom();
      }, 100);

      // 标记会话为已读
      const unreadIds = chatMessages
        .filter(msg => !msg.isRead)
        .map(msg => msg.messageId)
        .filter(id => !!id);
      
      if (unreadIds.length > 0) {
        this.markSessionAsRead(currentSession.sessionId, unreadIds);
      }

    } catch (error: any) {
      wx.hideLoading();
      console.error('加载聊天记录失败:', error);
      wx.showToast({
        title: error?.msg || '加载聊天记录失败',
        icon: 'none'
      });
    }
  },

  /**
   * 标记会话为已读
   */
  async markSessionAsRead(sessionId: string, messageIds?: string[]) {
    if (!sessionId) {
      return;
    }
    
    const validIds = Array.isArray(messageIds) ? messageIds.filter(id => !!id) : [];
    if (validIds.length === 0) {
      // 如果没有明确的消息ID，避免触发后端错误
      return;
    }
    
    try {
      await MerchantAPI.markMessagesRead(sessionId, validIds);
      
      // 更新本地消息列表中的未读状态
      const messages = this.data.messages.map(msg => {
        if (msg.sessionId === sessionId) {
          return {
            ...msg,
            unreadCount: 0,
            lastMessage: {
              ...msg.lastMessage,
              isRead: true
            }
          };
        }
        return msg;
      });
      
      this.setData({ messages });
      
      // 刷新统计数据
      this.loadMessageStatistics();
      
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  },


  /**
   * 发送消息
   */
  async sendMessage() {
    const { currentSession, messageInput } = this.data;
    
    if (!messageInput.trim()) {
      return;
    }

    if (!currentSession) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      });
      return;
    }

    // 保存消息内容用于失败回滚
    const messageContent = messageInput.trim();
    
    // 清空输入框
    this.setData({
      messageInput: ''
    });

    try {
      // 调用后端API：发送消息
      const response = await MerchantAPI.sendMessage(currentSession.sessionId, {
        content: messageContent,
        messageType: 'text'
      });

      if (response.code === 200) {
        // 发送成功，重新加载聊天记录以获取最新消息（包括刚发送的消息）
        await this.loadChatHistory(currentSession.sessionId);
        
        // 更新会话列表中的最后一条消息
        this.loadMessages(true);

        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 1500
        });
      } else {
        // 发送失败，恢复输入框内容
        this.setData({
          messageInput: messageContent
        });
        
        wx.showToast({
          title: response.msg || '发送失败，请重试',
          icon: 'none'
        });
      }

    } catch (error: any) {
      console.error('发送消息失败:', error);
      
      // 发送失败，恢复输入框内容
      this.setData({
        messageInput: messageContent
      });
      
      wx.showToast({
        title: error?.msg || '发送失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 显示优惠券列表
   */
  async showCouponList() {
    wx.showLoading({ title: '加载中...' });

    try {
      // 调用后端API：获取可用优惠券列表
      const response = await MerchantAPI.getAvailableCoupons();

      let coupons = [];

      if (response.code === 200 && response.data && response.data.length > 0) {
        coupons = response.data;
      } else {
        // 如果没有优惠券，使用模拟数据
        coupons = [
          {
            couponTemplateId: "CPN_TEMPLATE1001",
            name: "满30减5优惠券",
            description: "满30元可用，有效期30天",
            type: 1,
            discountValue: 5,
            validTo: "2023-12-31"
          },
          {
            couponTemplateId: "CPN_TEMPLATE1002", 
            name: "8.5折优惠券",
            description: "全场商品8.5折，最高减15元",
            type: 2,
            discountValue: 0.85,
            validTo: "2023-12-31"
          }
        ];
      }

      this.setData({
        showCouponModal: true,
        availableCoupons: coupons,
        customMessage: '为您送上专属优惠券'
      });

      wx.hideLoading();

    } catch (error) {
      console.error('加载优惠券列表失败:', error);
      wx.hideLoading();
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 选择优惠券
   */
  selectCoupon(e: any) {
    const coupon = e.currentTarget.dataset.coupon;
    this.setData({
      selectedCoupon: coupon
    });
  },

  /**
   * 发送优惠券
   */
  async sendCoupon() {
    const { currentSession, selectedCoupon, customMessage } = this.data;
    
    if (!selectedCoupon) {
      wx.showToast({
        title: '请选择优惠券',
        icon: 'none'
      });
      return;
    }

    if (!currentSession) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 调用后端API：发送优惠券
      const response = await MerchantAPI.sendCoupon(currentSession.sessionId, {
        couponTemplateId: selectedCoupon.couponTemplateId,
        customMessage: customMessage || '为您送上专属优惠券'
      });

      if (response.code === 200) {
        // 发送成功，重新加载聊天记录以获取最新消息
        this.loadChatHistory(currentSession.sessionId);
        
        // 更新会话列表中的最后一条消息
        this.loadMessages(true);

        this.setData({
          showCouponModal: false,
          selectedCoupon: null,
          customMessage: ''
        });

        wx.showToast({
          title: '优惠券发送成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: response.msg || '发送失败，请重试',
          icon: 'none'
        });
      }

    } catch (error) {
      console.error('发送优惠券失败:', error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 选择快捷回复
   */
  selectQuickReply(e: any) {
    const content = e.currentTarget.dataset.content;
    this.setData({
      messageInput: content
    });
  },

  /**
   * 滚动到底部
   */
  scrollToBottom() {
    if (this.data.chatMessages.length > 0) {
      const lastMessage = this.data.chatMessages[this.data.chatMessages.length - 1];
      this.setData({
        scrollIntoView: 'msg-' + lastMessage.messageId
      });
    }
  },

  /**
   * 按类型筛选
   */
  filterByType(e: any) {
    const type = e.currentTarget.dataset.type;
    
    // 这里可以实现筛选逻辑
    wx.showToast({
      title: `显示${type === 'customer' ? '顾客' : type === 'platform' ? '平台' : '群'}消息`,
      icon: 'none'
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.loadMessages(true);
  },

  /**
   * 加载更多消息
   */
  loadMoreMessages() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadMessages();
    }
  },

  /**
   * 打开设置
   */
  openSettings() {
    wx.navigateTo({
      url: '/pages/settings/settings'
    });
  },

  // 表单输入处理
  onMessageInput(e: any) {
    this.setData({
      messageInput: e.detail.value
    });
  },

  onCustomMessageInput(e: any) {
    this.setData({
      customMessage: e.detail.value
    });
  },

  // 弹窗控制
  closeChatModal() {
    this.setData({
      showChatModal: false,
      currentSession: null,
      chatMessages: [],
      messageInput: ''
    });
  },

  closeCouponModal() {
    this.setData({
      showCouponModal: false,
      selectedCoupon: null,
      customMessage: ''
    });
  },

  preventClose() {
    // 阻止事件冒泡
  }
});